package com.eightbears.beboy.base.view.citypicker;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.citypicker.adapter.CityListAdapter;
import com.eightbears.beboy.base.view.citypicker.adapter.ResultListAdapter;
import com.eightbears.beboy.base.view.citypicker.db.DBManager;
import com.eightbears.beboy.base.view.citypicker.model.City;
import com.eightbears.beboy.base.view.citypicker.model.LocateState;
import com.eightbears.beboy.base.view.citypicker.utils.StringUtils;
import com.eightbears.beboy.base.view.citypicker.view.SideLetterBar;
import com.eightbears.beboy.entity.StaticDataEntity;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Author Bro0cL on 2016/12/16.
 */
public class CityPickerActivity extends BaseActivity implements View.OnClickListener {
    public static final String KEY_PICKED_CITY = "picked_city";

    private ListView mListView;
    private ListView mResultListView;
    private EditText searchBox;
    private ImageView clearBtn;
    private ViewGroup emptyView;
    private SwipeBackLayout sw_finish;
    private LinearLayout ll_back;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<StaticDataEntity.Districts> districts;

    private AMapLocationClient mLocationClient;

    List<City> result = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cp_activity_city_list);

        initData();
        initView();
        initEvent();
        initLocation();
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String location = StringUtils.extractLocation(city, district);
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
                    } else {
                        //定位失败
                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    }
                }
            }
        });
        mLocationClient.startLocation();
    }

    protected void initData() {
        DBManager dbManager = new DBManager(this);
        dbManager.copyDBFile();

        initCityData();

    }

    private void initCityData() {

        List<StaticDataEntity.Districts> datas = new ArrayList<>();
        StaticDataEntity staticDataEntity = SPUtil.getStaticData();
        districts = staticDataEntity.getData().getPublic_districts();


        for (int i = 0; i < districts.size(); i++) {
            if (districts.get(i).getType().equals("2")) {
                StaticDataEntity.Districts temp = districts.get(i);
                String pingying = CommonUtils.toHanyuPinyin(temp.getName());
                temp.setPinyin(pingying);
                datas.add(temp);
            }
        }
        Collections.sort(datas, new CityComparator());
        mCityAdapter = new CityListAdapter(this, datas);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {
                back(name);
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                mLocationClient.startLocation();
            }
        });

        mResultAdapter = new ResultListAdapter(this, null);
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * sort by a-z
     */
    public class CityComparator implements Comparator<StaticDataEntity.Districts> {
        @Override
        public int compare(StaticDataEntity.Districts lhs, StaticDataEntity.Districts rhs) {
            String a = lhs.getPinyin().substring(0, 1);
            String b = rhs.getPinyin().substring(0, 1);
            return a.compareTo(b);
        }
    }

    protected void initView() {
        mListView = (ListView) findViewById(R.id.listview_all_city);
        sw_finish = (SwipeBackLayout) findViewById(R.id.sw_finish);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        ll_back = (LinearLayout) findViewById(R.id.ll_back);
        mListView.setAdapter(mCityAdapter);

        tv_title.setText("选择城市");
        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        SideLetterBar letterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        letterBar.setOverlay(overlay);
        letterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });

        searchBox = (EditText) findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                KLog.e(s);
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);

                    for (int i = 0; i < districts.size(); i++) {
                        if (districts.get(i).getType().equals("2")) {
                            if (districts.get(i).getName().contains(keyword)) {
                                KLog.e(districts.get(i).getName());
                                City city = new City(districts.get(i).getName(), "");
                                result.add(city);
                            }
                        }
                    }
                    if (result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                back(mResultAdapter.getItem(position).getName());
            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);

        clearBtn.setOnClickListener(this);
    }

    private void back(String city) {
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, city);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_search_clear) {
            searchBox.setText("");
            clearBtn.setVisibility(View.GONE);
            emptyView.setVisibility(View.GONE);
            mResultListView.setVisibility(View.GONE);
        } else if (i == R.id.back) {
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.closeInputMethod(this, searchBox);
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }
}

